package com.iotechn.unimall.admin.api.purchaseOrder;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.iotechn.unimall.core.annotation.HttpParam;
import com.iotechn.unimall.core.annotation.HttpParamType;
import com.iotechn.unimall.core.annotation.param.NotNull;
import com.iotechn.unimall.core.exception.AdminServiceException;
import com.iotechn.unimall.core.exception.ExceptionDefinition;
import com.iotechn.unimall.core.exception.ServiceException;
import com.iotechn.unimall.core.util.MoneyUtils;
import com.iotechn.unimall.data.domain.*;
import com.iotechn.unimall.data.dto.AdminDTO;
import com.iotechn.unimall.data.dto.purchase.PurchaseOperLogDTO;
import com.iotechn.unimall.data.dto.purchase.PurchaseOrderDTO;
import com.iotechn.unimall.data.dto.purchase.PurchaseOrderGoodsDTO;
import com.iotechn.unimall.data.mapper.*;
import com.iotechn.unimall.data.model.Page;
import com.iotechn.unimall.data.util.SessionUtil;
import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;


@Service
public class PurchaseOrderServiceImpl implements PurchaseOrderService {
    @Autowired
    private PurchaseOrderMapper purchaseOrderMapper;
    @Autowired
    private PurchaseOrderGoodsMapper purchaseOrderGoodsMapper;
    @Autowired
    private PurchaseOperLogMapper purchaseOperLogMapper;
    @Autowired
    private FinancePayableMapper financePayableMapper;
    @Autowired
    private WarehouseMapper warehouseMapper;
    @Autowired
    private WarehouseGoodsMapper warehouseGoodsMapper;
    @Autowired
    private SupplierMapper supplierMapper;
    @Autowired
    private PurchaseWarehouseOperLogMapper purchaseWarehouseOperLogMapper;
    @Autowired
    private SkuMapper skuMapper;

/*
    @Autowired
    private TaxrateMapper taxrateMapper;
*/

    @Autowired
    private PurchaseWarehouseOrderMapper purchaseWarehouseOrderMapper;
    @Autowired
    private PurchaseWarehouseOrderGoodsMapper purchaseWarehouseOrderGoodsMapper;

    @Override
    public Page<PurchaseOrderDO> list(Integer page, Integer limit, Long adminId) throws ServiceException {
        Wrapper<PurchaseOrderDO> wrapper = new EntityWrapper<PurchaseOrderDO>();
        /**if (!StringUtils.isEmpty(name)) {
         wrapper.like("username", name);
         }**/
        wrapper.orderBy("id", false);
        Integer count = purchaseOrderMapper.selectCount(wrapper);
        List<PurchaseOrderDO> PurchaseOrderDOS = purchaseOrderMapper.selectPage(new RowBounds((page - 1) * limit, limit), wrapper);
        return new Page<>(PurchaseOrderDOS, page, limit, count);
    }

    /**
     * purchaseOrderDO: {"purchaseOrderGoodsDTOS":[{"barCode":" 6970835581101","goodsId":1237622,"goodsName":"三明治香草味（光合） 个","goodsTotalPrice":0,"id":1237622,"img":"https://shopmallimg.oss-cn-shanghai.aliyuncs.com/bg/376b78a2077346c3b6df273815a7bc20.jpg","skuId":4076,"skuName":"个","spuId":1237622,"spuName":"三明治香草味（光合）","unit":"个","pGoodsBuyNum":"1","pGoodsAmount":"1","pGoodsPrice":null}],"totalPrice":1,"total":1,"warehouseOrderConpon":0,"warehouseId":23,"warehouseIsSelected":false,"supplierId":9,"orderState":0,"supplierName":"仝海米业","supplierContacts":"夏镇长","supplierPhone":"222222","pOrderConpon":"0"}
     *
     * @param purchaseOrderDTO
     * @param adminId
     * @return
     * @throws ServiceException
     */

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String create(PurchaseOrderDTO purchaseOrderDTO, Long adminId) throws ServiceException {
        //参数校验
        if (CollectionUtils.isEmpty(purchaseOrderDTO.getPurchaseOrderGoodsDTOS())) {
            //未选择入库商品
            throw new AdminServiceException(ExceptionDefinition.ADMIN_UNKNOWN_EXCEPTION);
        }
        BigDecimal ratio = new BigDecimal(Float.toString(100.00f));
        Date now = new Date();
        PurchaseOrderDO purchaseOrderDO = new PurchaseOrderDO();
        BeanUtils.copyProperties(purchaseOrderDTO, purchaseOrderDO);
        purchaseOrderDO.setGmtUpdate(now);
        purchaseOrderDO.setGmtCreate(now);
        purchaseOrderDO.setAdminId(adminId);
        purchaseOrderDO.setOrderState(0);//待入库
        purchaseOrderDO.setPOrderNo("CG" + System.currentTimeMillis());//入库单编号自动生成
        //purchaseOrderDO.setOrderPaymentCode("");//支付方式待定
      /*  purchaseOrderDO.setPOrderGoodsAmount(ratio.multiply(new BigDecimal(Float.toString(purchaseOrderDTO.getTotalPrice()))).longValue());
        purchaseOrderDO.setPOrderConpon(purchaseOrderDTO.getPOrderConpon() == null ? 0 : (int) (purchaseOrderDTO.getPOrderConpon() * 100));
        Float orderAmount = ratio.multiply(new BigDecimal(Float.toString(purchaseOrderDTO.getTotalPrice()))).floatValue() - (purchaseOrderDTO.getPOrderConpon() == null ? 0 : ratio.multiply(new BigDecimal(Float.toString(purchaseOrderDTO.getPOrderConpon()))).floatValue());
        purchaseOrderDO.setPOrderAmount(new BigDecimal(Float.toString(orderAmount)).longValue());
        purchaseOrderDO.setPOrderGoodsAmount((new BigDecimal(Float.toString(orderAmount))).longValue());
      */  //操作人真实姓名
        AdminDTO adminDTO = SessionUtil.getAdmin();
        if (adminDTO != null) {
            purchaseOrderDO.setAdminRealname(adminDTO.getRealname());
        }
        if (purchaseOrderMapper.insert(purchaseOrderDO) > 0) {
            //插入入库商品表
            for (PurchaseOrderGoodsDTO purchaseOrderGoodsDTO : purchaseOrderDTO.getPurchaseOrderGoodsDTOS()) {
                PurchaseOrderGoodsDO purchaseOrderGoodsDO = new PurchaseOrderGoodsDO();
                BeanUtils.copyProperties(purchaseOrderGoodsDTO, purchaseOrderGoodsDO);
                purchaseOrderGoodsDO.setPOrderId(purchaseOrderDO.getId());
                //purchaseOrderGoodsDO.setPId(purchaseOrderDO.getWarehouseId());
                purchaseOrderGoodsDO.setBarCode(purchaseOrderGoodsDTO.getBarCode());// 商品编码为条形码
                purchaseOrderGoodsDO.setSkuId(purchaseOrderGoodsDTO.getSkuId());
                purchaseOrderGoodsDO.setGoodsImg(purchaseOrderGoodsDTO.getImg());
                purchaseOrderGoodsDO.setGoodsUnit(purchaseOrderGoodsDTO.getUnit());
          /*      purchaseOrderGoodsDO.setPGoodsPrice((long) (Float.valueOf(purchaseOrderGoodsDTO.getPGoodsPrice()) * 100));
                purchaseOrderGoodsDO.setPGoodsAmount((long) (purchaseOrderGoodsDTO.getPGoodsAmount() * 100));
          */      purchaseOrderGoodsDO.setGmtCreate(now);
                purchaseOrderGoodsDO.setGmtUpdate(now);
                purchaseOrderGoodsMapper.insert(purchaseOrderGoodsDO);
            }
            //插入操作表
            //操作人真实姓名
            if (adminDTO != null) {
                purchaseOrderDO.setAdminRealname(adminDTO.getRealname());
                insertPurchaseOperLog(purchaseOrderDO, adminDTO);
            }
            return "ok";
        }
        throw new AdminServiceException(ExceptionDefinition.ADMIN_UNKNOWN_EXCEPTION);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String update(PurchaseOrderDTO purchaseOrderDTO, Long adminId) throws ServiceException {
        Long id = purchaseOrderDTO.getId();
        if (id == null) {
            return "fail";
        }

        BigDecimal ratio = new BigDecimal(Float.toString(100.00f));
        Date now = new Date();
        PurchaseOrderDO purchaseOrderDO = new PurchaseOrderDO();
        BeanUtils.copyProperties(purchaseOrderDTO, purchaseOrderDO);
        purchaseOrderDO.setGmtUpdate(now);
        purchaseOrderDO.setAdminId(adminId);
       /* purchaseOrderDO.setPOrderGoodsAmount(ratio.multiply(new BigDecimal(Float.toString(purchaseOrderDTO.getTotalPrice()))).longValue());
        purchaseOrderDO.setPOrderConpon(purchaseOrderDTO.getPOrderConpon() == null ? 0 : (int) (purchaseOrderDTO.getPOrderConpon() * 100));
        Float warehouseOrderAmount = ratio.multiply(new BigDecimal(Float.toString(purchaseOrderDTO.getTotalPrice()))).floatValue() - (purchaseOrderDTO.getPOrderConpon() == null ? 0 : ratio.multiply(new BigDecimal(Float.toString(purchaseOrderDTO.getPOrderConpon()))).floatValue());
        purchaseOrderDO.setPOrderAmount(new BigDecimal(Float.toString(warehouseOrderAmount)).longValue());
        purchaseOrderDO.setPOrderGoodsAmount((new BigDecimal(Float.toString(warehouseOrderAmount))).longValue());
       */ //删除入库单-商品数据
        purchaseOrderDO.setGmtUpdate(now);
        List<Long> doGoodsIds = new LinkedList<>();
        doGoodsIds = purchaseOrderDTO.getPurchaseOrderGoodsDTOS().stream().map(PurchaseOrderGoodsDTO::getId).distinct().collect(Collectors.toList());
        purchaseOrderGoodsMapper.delete(new EntityWrapper<PurchaseOrderGoodsDO>()
                .eq("p_order_id", purchaseOrderDTO.getId()).notIn("id",doGoodsIds));
        if (purchaseOrderMapper.updateById(purchaseOrderDO) > 0) {
            //更新时先删除入库单-商品
            for (PurchaseOrderGoodsDTO purchaseOrderGoodsDTO : purchaseOrderDTO.getPurchaseOrderGoodsDTOS()) {
                PurchaseOrderGoodsDO purchaseOrderGoodsDO = new PurchaseOrderGoodsDO();
                BeanUtils.copyProperties(purchaseOrderGoodsDTO, purchaseOrderGoodsDO);
                purchaseOrderGoodsDO.setPOrderId(purchaseOrderDO.getId());
                //purchaseOrderGoodsDO.setPId(purchaseOrderDO.getWarehouseId());
                purchaseOrderGoodsDO.setBarCode(purchaseOrderGoodsDTO.getBarCode());// 商品编码为条形码
                purchaseOrderGoodsDO.setGoodsImg(purchaseOrderGoodsDTO.getImg());
                purchaseOrderGoodsDO.setGoodsUnit(purchaseOrderGoodsDTO.getUnit());
                purchaseOrderGoodsDO.setSkuId(purchaseOrderGoodsDTO.getSkuId());
             /*   purchaseOrderGoodsDO.setPGoodsPrice(new BigDecimal(Float.toString(purchaseOrderGoodsDTO.getPGoodsPrice())).longValue());
                purchaseOrderGoodsDO.setPGoodsAmount(new BigDecimal(Float.toString(purchaseOrderGoodsDTO.getPGoodsAmount())).longValue());
             */   purchaseOrderGoodsDO.setGmtCreate(now);
                purchaseOrderGoodsDO.setGmtUpdate(now);
                if(purchaseOrderGoodsDO.getId()>0){
                    purchaseOrderGoodsMapper.updateById(purchaseOrderGoodsDO);
                }else {
                    purchaseOrderGoodsMapper.insert(purchaseOrderGoodsDO);
                }
             }
            //操作人真实姓名
            AdminDTO adminDTO = SessionUtil.getAdmin();
            if (adminDTO != null) {
                purchaseOrderDO.setAdminRealname(adminDTO.getRealname());
                insertPurchaseOperLog(purchaseOrderDO, adminDTO);
            }
            return "ok";
        }
        throw new AdminServiceException(ExceptionDefinition.ADMIN_UNKNOWN_EXCEPTION);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String delete(Long id, Long adminId) throws ServiceException {
        PurchaseOrderDO purchaseOrderDO = purchaseOrderMapper.selectById(id);
        if(purchaseOrderDO.getOrderState()>0){
            throw new AdminServiceException(ExceptionDefinition.PUCHASE_STATE_EXCEPTION);

        }
        if (purchaseOrderMapper.deleteById(id) > 0) {
            purchaseOrderGoodsMapper.delete(new EntityWrapper<PurchaseOrderGoodsDO>()
                    .eq("p_order_id", id));
            return "ok";
        }
        throw new AdminServiceException(ExceptionDefinition.ADMIN_UNKNOWN_EXCEPTION);

    }

    @Override
    public PurchaseOrderDTO detail(Long id, Long adminId) throws ServiceException {
        PurchaseOrderDO purchaseOrderDO = purchaseOrderMapper.selectById(id);
        PurchaseOrderDTO purchaseOrderDTO = new PurchaseOrderDTO();
        BeanUtils.copyProperties(purchaseOrderDO, purchaseOrderDTO);
        //价格金额处理
        purchaseOrderDTO.setPOrderConpon(purchaseOrderDO.getPOrderConpon() == null ? 0 : purchaseOrderDO.getPOrderConpon() / 100.00f);
        purchaseOrderDTO.setPOrderAmount((Float.valueOf(purchaseOrderDO.getPOrderAmount()) / 100));
        purchaseOrderDTO.setPOrderGoodsAmount(Float.valueOf(purchaseOrderDO.getPOrderGoodsAmount()) / 100);
        WarehouseDO warehouseDO = warehouseMapper.selectById(purchaseOrderDO.getWarehouseId());
        if (warehouseDO != null) {
            purchaseOrderDTO.setWarehouseName(warehouseDO.getWarehouseName());
        }
        SupplierDO supplierDO = supplierMapper.selectById(purchaseOrderDO.getSupplierId());
        if (supplierDO != null) {
            purchaseOrderDTO.setSupplierName(supplierDO.getSupplierName());
        }
        if(StringUtils.isEmpty(purchaseOrderDTO.getWarehouseName()) || StringUtils.isEmpty(purchaseOrderDTO.getSupplierName())){
            throw new AdminServiceException(ExceptionDefinition.NO_WAREHOUSE_SUPPILED_ERROR);
        }
        //通过采购单获取商品
        List<PurchaseOrderGoodsDTO> purchaseOrderGoodsDTOS = purchaseOrderGoodsMapper.querySkusByPara(id, null, null, null);
        //价格处理
        purchaseOrderGoodsDTOS.stream().map(i -> {
            i.setPGoodsPrice((Float.valueOf(i.getPGoodsPrice()) / 100));
            i.setPGoodsAmount((Float.valueOf(i.getPGoodsAmount()) / 100));
            return i;
        }).collect(Collectors.toList());
        purchaseOrderDTO.setPurchaseOrderGoodsDTOS(purchaseOrderGoodsDTOS);
        //操作日志
        List<PurchaseOperLogDTO> purchaseWarehouseOperLogDTOS = purchaseOperLogMapper.listOrderLogsByPara(id);
        purchaseOrderDTO.setPurchaseOperLogDTOS(purchaseWarehouseOperLogDTOS);
        return purchaseOrderDTO;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String audit(
            @NotNull @HttpParam(name = "pOrderId", description = "采购单ID") Long pOrderId,
            @HttpParam(name = "orderState", description = "采购单状态") Integer orderState,
            @HttpParam(name = "auditComment", description = "审核意见") String auditComment,
            @NotNull @HttpParam(name = "adminId", type = HttpParamType.ADMIN_ID, description = "管理员ID") Long adminId) throws ServiceException {

        if (pOrderId == null || "".equals(pOrderId)) {
            return "fail";
        }
        PurchaseOrderDO purchaseOrderDO = purchaseOrderMapper.selectById(pOrderId);
        if (purchaseOrderDO == null) {
            return "fail";
        }
        purchaseOrderDO.setOrderState(orderState);
        purchaseOrderDO.setPOrderAuditComment(auditComment);
        Date now = new Date();
        AdminDTO adminDTO = SessionUtil.getAdmin();
        boolean isPassed = purchaseOrderDO.getOrderState() == 1;
        if (adminDTO != null && isPassed) {
            if (purchaseOrderDO.getPOrderAuditUserId() == null) {
                purchaseOrderDO.setPOrderAuditUserId(adminId);
                purchaseOrderDO.setPOrderAuditTime(now);
                purchaseOrderDO.setPOrderAuditRealname(adminDTO.getRealname());
            }
        }
        if (purchaseOrderMapper.updateById(purchaseOrderDO) > 0) {
            if (isPassed) {//通过
                //插入应付记录
               /* FinancePayableDO financePayableDO = new FinancePayableDO();
                financePayableDO.setGmtUpdate(now);
                financePayableDO.setAdminId(adminId);
                financePayableDO.setAdminName(adminDTO.getRealname());
                financePayableDO.setFinishAmount(0);
                financePayableDO.setAddTime(purchaseOrderDO.getPOrderAuditTime());
                financePayableDO.setPaymentCode("");
                financePayableDO.setSupplierId(purchaseOrderDO.getSupplierId());
                financePayableDO.setPaymentYouhuiAmount(purchaseOrderDO.getPOrderConpon());
                financePayableDO.setSupplierName(purchaseOrderDO.getSupplierName());
                financePayableDO.setPOrderId(purchaseOrderDO.getId());
                financePayableDO.setPOrderNo(purchaseOrderDO.getPOrderNo());
                financePayableDO.setPaymentAllAmount(purchaseOrderDO.getPOrderGoodsAmount().intValue());
                financePayableDO.setPaymentAmount(purchaseOrderDO.getPOrderAmount().intValue());
                financePayableMapper.insert(financePayableDO);
*/

            }
            //插入操作表
            //操作人真实姓名
            if (adminDTO != null) {
                insertPurchaseOperLog(purchaseOrderDO, adminDTO);
            }
            return "ok";
        }
        throw new AdminServiceException(ExceptionDefinition.ADMIN_UNKNOWN_EXCEPTION);

    }

    /**
     * 插入操作日志 -采购单
     *
     * @throws Exception
     */
    private void insertPurchaseOperLog(PurchaseOrderDO purchaseOrderDO, AdminDTO adminDTO) {
        PurchaseOperLogDO purchaseOrderOperLogDO = new PurchaseOperLogDO();
        purchaseOrderOperLogDO.setPOrderId(purchaseOrderDO.getId());
        purchaseOrderOperLogDO.setGmtCreate(new Date());
        purchaseOrderOperLogDO.setOperTime(new Date());
        purchaseOrderOperLogDO.setOperUserId(adminDTO.getId());
        purchaseOrderOperLogDO.setOperUser(adminDTO.getRealname());
        purchaseOrderOperLogDO.setOrderState(purchaseOrderDO.getOrderState());
        purchaseOperLogMapper.insert(purchaseOrderOperLogDO);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String updateConform(PurchaseOrderDTO purchaseOrderDTO, Long adminId) throws ServiceException {
        Long id = purchaseOrderDTO.getId();
        if (id == null) {
            return "fail";
        }
        BigDecimal ratio = new BigDecimal(Float.toString(100.00f));
        Date now = new Date();
        PurchaseOrderDO purchaseOrderDO = new PurchaseOrderDO();
        BeanUtils.copyProperties(purchaseOrderDTO, purchaseOrderDO);
        purchaseOrderDO.setGmtUpdate(now);
        purchaseOrderDO.setAdminId(adminId);
        Float warehouseOrderAmount = ratio.multiply(new BigDecimal(Float.toString(purchaseOrderDTO.getTotalPrice()))).floatValue() - (purchaseOrderDTO.getPOrderConpon() == null ? 0 : ratio.multiply(new BigDecimal(Float.toString(purchaseOrderDTO.getPOrderConpon()))).floatValue());
        purchaseOrderDO.setPOrderAmount(new BigDecimal(Float.toString(warehouseOrderAmount)).longValue());
        purchaseOrderDO.setPOrderGoodsAmount((new BigDecimal(Float.toString(warehouseOrderAmount))).longValue());
        purchaseOrderDTO.setPOrderAmount(purchaseOrderDTO.getTotalPrice());
        purchaseOrderDTO.setPOrderGoodsAmount(purchaseOrderDTO.getTotalPrice());
        purchaseOrderDO.setGmtUpdate(now);
        //计算采购总数
        Float pOrderGoodsCount=0F;
        for (PurchaseOrderGoodsDTO purchaseOrderGoodsDTO : purchaseOrderDTO.getPurchaseOrderGoodsDTOS()){
            pOrderGoodsCount = pOrderGoodsCount + purchaseOrderGoodsDTO.getPGoodsActualNum();
        }
        purchaseOrderDO.setPOrderGoodsCount(pOrderGoodsCount);
        if (purchaseOrderMapper.updateById(purchaseOrderDO) > 0) {
            //更新时只更新商品
            for (PurchaseOrderGoodsDTO purchaseOrderGoodsDTO : purchaseOrderDTO.getPurchaseOrderGoodsDTOS()) {
                PurchaseOrderGoodsDO purchaseOrderGoodsDO = new PurchaseOrderGoodsDO();
                BeanUtils.copyProperties(purchaseOrderGoodsDTO, purchaseOrderGoodsDO);
                purchaseOrderGoodsDO.setId(purchaseOrderGoodsDTO.getId());
                purchaseOrderGoodsDO.setPOrderId(purchaseOrderDO.getId());
                if(purchaseOrderGoodsDTO.getPGoodsActualNum()!=null && purchaseOrderGoodsDTO.getPGoodsActualNum()>0){
                    purchaseOrderGoodsDO.setPGoodsActualNum(purchaseOrderGoodsDTO.getPGoodsActualNum());
                    purchaseOrderGoodsDO.setGoodsImg(purchaseOrderGoodsDTO.getGoodsImg());
                    purchaseOrderGoodsDO.setPGoodsAmount(ratio.multiply(new BigDecimal(Float.toString(purchaseOrderGoodsDTO.getPGoodsAmount()))).longValue());
                    purchaseOrderGoodsDO.setPGoodsPrice(ratio.multiply(new BigDecimal(Float.toString(purchaseOrderGoodsDTO.getPGoodsAmount()/purchaseOrderGoodsDTO.getPGoodsActualNum()))).longValue());
                }
                purchaseOrderGoodsMapper.updateById(purchaseOrderGoodsDO);
            }
            //操作人真实姓名
            AdminDTO adminDTO = SessionUtil.getAdmin();
            if (adminDTO != null) {
                purchaseOrderDO.setAdminRealname(adminDTO.getRealname());
                insertPurchaseOperLog(purchaseOrderDO, adminDTO);
            }
            if(purchaseOrderDTO.getOrderState()==2) {
                purchaseOrderDTO = purchaseOrderMapper.selectOrderById(purchaseOrderDO.getId());
                List<PurchaseOrderGoodsDTO> purchaseOrderGoodsDTOS = purchaseOrderGoodsMapper.querySkusByPara(purchaseOrderDO.getId(), null, null, null);
                purchaseOrderDTO.setPurchaseOrderGoodsDTOS(purchaseOrderGoodsDTOS);
                purchaseOrderDTO.setTotal(pOrderGoodsCount);
                addWahoureseOrder(purchaseOrderDTO, adminId);
            }
            return "ok";
        }
        throw new AdminServiceException(ExceptionDefinition.ADMIN_UNKNOWN_EXCEPTION);
    }

    public void addWahoureseOrder(PurchaseOrderDTO purchaseOrderDTO, Long adminId) {
       // List<TaxrateDO> taxrateDOS = taxrateMapper.selectList(null);
        //BigDecimal ratio = new BigDecimal(Float.toString(100.00f));
        Date now = new Date();
        PurchaseWarehouseOrderDO purchaseWarehouseOrderDO = new PurchaseWarehouseOrderDO();
        purchaseWarehouseOrderDO.setPOrderId(purchaseOrderDTO.getId());
        purchaseWarehouseOrderDO.setGmtUpdate(now);
        purchaseWarehouseOrderDO.setGmtCreate(now);
        purchaseWarehouseOrderDO.setWarehouseOrderInsertTime(now);
        purchaseWarehouseOrderDO.setAdminId(adminId);
        purchaseWarehouseOrderDO.setWarehouseId(purchaseOrderDTO.getWarehouseId());
        purchaseWarehouseOrderDO.setWarehouseOrderState(0);//待入库
        purchaseWarehouseOrderDO.setWarehouseOrderNo("RK" + System.currentTimeMillis());//入库单编号自动生成
        purchaseWarehouseOrderDO.setWarehouseOrderPaymentCode("");//支付方式待定
        purchaseWarehouseOrderDO.setWarehouseOrderGoodsAmount(new BigDecimal(Float.toString(purchaseOrderDTO.getPOrderGoodsAmount())).longValue());
        purchaseWarehouseOrderDO.setWarehouseOrderGoodsCount(purchaseOrderDTO.getTotal());
        purchaseWarehouseOrderDO.setWarehouseOrderConpon(purchaseOrderDTO.getPOrderConpon() == null ? 0 : (int) (purchaseOrderDTO.getPOrderConpon() * 100));
        purchaseWarehouseOrderDO.setWarehouseOrderAmount(new BigDecimal(Float.toString(purchaseOrderDTO.getPOrderAmount())).longValue());
        purchaseWarehouseOrderDO.setWarehouseOrderGoodsAmount((new BigDecimal(Float.toString(purchaseOrderDTO.getPOrderGoodsAmount()))).longValue());
        purchaseWarehouseOrderDO.setSupplierId(purchaseOrderDTO.getSupplierId());
        purchaseWarehouseOrderDO.setWarehouseOrderGoodsCount(purchaseOrderDTO.getTotal());
        purchaseWarehouseOrderDO.setSupplierId(purchaseOrderDTO.getSupplierId());
        purchaseWarehouseOrderDO.setSupplierName(purchaseOrderDTO.getSupplierName());
        purchaseWarehouseOrderDO.setSupplierContacts(purchaseOrderDTO.getSupplierContacts());
        //操作人真实姓名
        AdminDTO adminDTO = SessionUtil.getAdmin();
        if (adminDTO != null) {
            purchaseWarehouseOrderDO.setAdminRealname(adminDTO.getRealname());
        }
        Long orderGoodsAmount = purchaseWarehouseOrderDO.getWarehouseOrderGoodsAmount();//makeTaxrate(taxrateDOS, purchaseWarehouseOrderDO.getWarehouseOrderGoodsAmount());
        if(orderGoodsAmount.longValue() > 0l){
            purchaseWarehouseOrderDO.setWarehouseOrderGoodsAmount(orderGoodsAmount);
        }
        if (purchaseWarehouseOrderMapper.insert(purchaseWarehouseOrderDO) > 0) {
            //插入入库商品表
            for (PurchaseOrderGoodsDTO purchaseOrderGoodsDTO : purchaseOrderDTO.getPurchaseOrderGoodsDTOS()) {
                PurchaseWarehouseOrderGoodsDO purchaseWarehouseOrderGoodsDO = new PurchaseWarehouseOrderGoodsDO();
                purchaseWarehouseOrderGoodsDO.setWarehouseOrderId(purchaseWarehouseOrderDO.getId());
                purchaseWarehouseOrderGoodsDO.setWarehouseId(purchaseWarehouseOrderDO.getWarehouseId());
                purchaseWarehouseOrderGoodsDO.setGoodsNo(purchaseOrderGoodsDTO.getBarCode());// 商品编码为条形码
                purchaseWarehouseOrderGoodsDO.setGoodsBarCode(purchaseOrderGoodsDTO.getBarCode());
                purchaseWarehouseOrderGoodsDO.setGoodsId(purchaseOrderGoodsDTO.getGoodsId());
                purchaseWarehouseOrderGoodsDO.setSkuId(purchaseOrderGoodsDTO.getSkuId());
                purchaseWarehouseOrderGoodsDO.setGoodsImg(purchaseOrderGoodsDTO.getGoodsImg());
                purchaseWarehouseOrderGoodsDO.setGoodsUnit(purchaseOrderGoodsDTO.getGoodsUnit());
                purchaseWarehouseOrderGoodsDO.setWarehouseGoodsAmount(new BigDecimal(Float.toString(purchaseOrderGoodsDTO.getPGoodsAmount())).longValue());
                purchaseWarehouseOrderGoodsDO.setWarehouseGoodsBuyNum(purchaseOrderGoodsDTO.getPGoodsActualNum());
                purchaseWarehouseOrderGoodsDO.setGoodsName(purchaseOrderGoodsDTO.getGoodsName());
                purchaseWarehouseOrderGoodsDO.setSkuName(purchaseOrderGoodsDTO.getSkuName());
                purchaseWarehouseOrderGoodsDO.setSpuName(purchaseOrderGoodsDTO.getSpuName());
                purchaseWarehouseOrderGoodsDO.setGoodsId(purchaseOrderGoodsDTO.getGoodsId());
                Long averPrice = 0l;
                List<WarehouseGoodsDO> warehouseGoodsDOS = warehouseGoodsMapper.selectList(new EntityWrapper<WarehouseGoodsDO>().eq("sku_id", purchaseOrderGoodsDTO.getSkuId()).eq("warehouse_id", purchaseOrderGoodsDTO.getWarehouseId()));
                WarehouseGoodsDO warehouseGoodsDO = new WarehouseGoodsDO();
                //当前平均价
                Float averPriceF = 0f;
                //当前库存
                Float warehouseSkuNum = 0f;
                if (warehouseGoodsDOS != null && warehouseGoodsDOS.size() > 0) {
                    warehouseGoodsDO = warehouseGoodsDOS.get(0);
                }
                if (warehouseGoodsDO.getPrice() == null || "".equals(warehouseGoodsDO.getPrice())) {
                    averPrice = MoneyUtils.mul(MoneyUtils.div(purchaseWarehouseOrderGoodsDO.getWarehouseGoodsAmount().doubleValue(), purchaseWarehouseOrderGoodsDO.getWarehouseGoodsBuyNum().doubleValue(), 3), 1d).longValue();
                } else {
                    averPriceF = warehouseGoodsDO.getPrice().floatValue();
                    warehouseSkuNum = warehouseGoodsDO.getWarehouseSkuStock();
                    //此次入库商品总价
                    Float goodsTotalPrice = purchaseWarehouseOrderGoodsDO.getWarehouseGoodsAmount().floatValue();
                    //计算总数
                    Float avgNum = MoneyUtils.add(warehouseSkuNum.doubleValue(), purchaseWarehouseOrderGoodsDO.getWarehouseGoodsBuyNum().doubleValue()).floatValue();

                    Float avgPrice = MoneyUtils.add(MoneyUtils.mul(averPriceF.doubleValue(), warehouseSkuNum.doubleValue()), goodsTotalPrice.doubleValue()).floatValue();

                    averPrice = MoneyUtils.div(avgPrice.doubleValue(), avgNum.doubleValue(), 3).longValue();
                }

                purchaseWarehouseOrderGoodsDO.setGoodsAverPrice(averPrice);//入库时如果没有平均价格说明第一次入库，平均价格为当前价格
                purchaseWarehouseOrderGoodsDO.setWarehouseGoodsPrice(Float.valueOf(purchaseOrderGoodsDTO.getPGoodsPrice()).longValue());
                //purchaseWarehouseOrderGoodsDO.setWarehouseGoodsAmount((long) (Float.valueOf(purchaseOrderGoodsDTO.getPGoodsPrice()) * Float.valueOf(purchaseOrderGoodsDTO.getPGoodsActualNum())));
                purchaseWarehouseOrderGoodsDO.setWarehouseGoodsAmount((long) (purchaseOrderGoodsDTO.getPGoodsAmount().longValue()));
                purchaseWarehouseOrderGoodsDO.setGoodsPreAverPrice(warehouseGoodsDO.getPrice());
                purchaseWarehouseOrderGoodsDO.setGmtCreate(now);
                purchaseWarehouseOrderGoodsDO.setGmtUpdate(now);
                Long goodsAmount = purchaseWarehouseOrderGoodsDO.getWarehouseGoodsAmount();//makeTaxrate(taxrateDOS, purchaseWarehouseOrderGoodsDO.getWarehouseGoodsAmount());
                if(goodsAmount.longValue() > 0l){
                    purchaseWarehouseOrderGoodsDO.setWarehouseGoodsAmount(goodsAmount);
                    Double price = MoneyUtils.div(goodsAmount.doubleValue(), purchaseWarehouseOrderGoodsDO.getWarehouseGoodsBuyNum().doubleValue(), 2);
                    purchaseWarehouseOrderGoodsDO.setWarehouseGoodsPrice(price.longValue());
                }
                purchaseWarehouseOrderGoodsMapper.insert(purchaseWarehouseOrderGoodsDO);
            }
            //插入操作表
            //操作人真实姓名
            if (adminDTO != null) {
                purchaseWarehouseOrderDO.setAdminRealname(adminDTO.getRealname());
                insertPurchaseWarehouseOperLog(purchaseWarehouseOrderDO, adminDTO);
            }
        }
    }
    /**
     * 插入操作日志 仓库-入库单
     *
     * @throws Exception
     */
    private void insertPurchaseWarehouseOperLog(PurchaseWarehouseOrderDO purchaseWarehouseOrderDO, AdminDTO adminDTO) {
        PurchaseWarehouseOperLogDO purchaseWarehouseOperLogDO = new PurchaseWarehouseOperLogDO();
        purchaseWarehouseOperLogDO.setPurcahseWarehouseOrderId(purchaseWarehouseOrderDO.getId());
        purchaseWarehouseOperLogDO.setGmtCreate(new Date());
        purchaseWarehouseOperLogDO.setOperUserId(adminDTO.getId());
        purchaseWarehouseOperLogDO.setOperUser(adminDTO.getRealname());
        purchaseWarehouseOperLogDO.setOperUserUsername(adminDTO.getUsername());
        purchaseWarehouseOperLogDO.setStatus(purchaseWarehouseOrderDO.getWarehouseOrderState());
        purchaseWarehouseOperLogMapper.insert(purchaseWarehouseOperLogDO);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public String towareHouseOrder(Long pOrderId, Long adminId) throws ServiceException {
        PurchaseOrderDTO purchaseOrderDTO = purchaseOrderMapper.selectOrderById(pOrderId);
        if(purchaseOrderDTO.getOrderState().intValue() == 1) {
            purchaseOrderDTO = purchaseOrderMapper.selectOrderById(pOrderId);
            List<PurchaseOrderGoodsDTO> purchaseOrderGoodsDTOS = purchaseOrderGoodsMapper.querySkusByPara(pOrderId, null, null, null);
            purchaseOrderDTO.setPurchaseOrderGoodsDTOS(purchaseOrderGoodsDTOS);
            addWahoureseOrder(purchaseOrderDTO, adminId);
            return "ok";

        }else{
            return "fail";

        }

    }

    /**
     * 计算税
     * @param taxrateDOS
     * @param
     * @return
     */
   /* public Long makeTaxrate(List<TaxrateDO> taxrateDOS,Long warehouseGoodsAmount){
        if(taxrateDOS.size() > 0){
            TaxrateDO taxrateDO = taxrateDOS.get(0);
            if(taxrateDO != null && taxrateDO.getTaxrate() != null){
                BigDecimal amount = new BigDecimal(warehouseGoodsAmount);//原金额
                BigDecimal taxrate = taxrateDO.getTaxrate();// 税率
                BigDecimal multiply = taxrate.multiply(amount);//税额
                BigDecimal add = amount.add(multiply);
                return add.longValue();
            }
        }
        return 0L;
    }*/
}

